<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>遍历过程中key的作用</title>
</head>

<body>
    <div id="app"></div>

    <script src="../../00_课程资料/js@17.0.2/react.development.js"></script>
    <script src="../../00_课程资料/js@17.0.2/react-dom.development.js"></script>
    <script src="../../00_课程资料/js@17.0.2/babel.min.js"></script>

    <script type="text/babel">
        class Person extends React.Component {
            state = {
                persons: [
                    {
                        id: 0,
                        name: '李四',
                        age: 18
                    },
                    {
                        id: 1,
                        name: '张三',
                        age: 19
                    },
                ]
            }
            add = () => {
                const { persons } = this.state
                const wang = {
                    id: 2,
                    name: '小王',
                    age: 20
                }
                this.setState({
                    persons: [wang, ...persons]
                })
            }
            render() {
                return (
                    <div>
                        <button onClick={this.add}>添加小王</button>
                        <h3>用index索引值作为key</h3>
                        <ul>
                            {
                                this.state.persons.map((item, index) => {
                                    return (
                                        <li key={index}>
                                            <span>{item.name} - {item.age}</span>
                                            <input type="text" />
                                        </li>
                                    )
                                })
                            }
                        </ul>
                        <h3>用id唯一值作为key</h3>
                        <ul>
                            {
                                this.state.persons.map((item, index) => {
                                    return (
                                        <li key={item.id}>
                                            <span>{item.name} - {item.age}</span>
                                            <input type="text" />
                                        </li>
                                    )
                                })
                            }
                        </ul>
                    </div>
                )
            }
        }

        ReactDOM.render(<Person />, document.getElementById('app'))
    </script>
</body>

</html>